<?php

namespace app\modules\backend\controllers;

use Yii;
use app\tools\Re;
use app\models\User;
use app\models\Identity;
use app\models\Address;
use app\models\AuthItemChild;
use app\models\AuthAssignment;
use app\models\UserLogin;
use app\models\PhoneCode;
use app\models\CompanyInfo;
use app\models\UserAuthRecord;
use app\models\traits\Img;
use app\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
use vendor\phpqrcode\QRcode;

class UserController extends BaseController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            $behaviors['authenticator'] = [
                'class' => HttpBearerAuth::class,
                'optional' => [
                    'login',
                ],
            ];
        }
        return $behaviors;
    }

    /**
     * 登录接口(账号密码)
     */
    public function actionLogin(){
        $username = Yii::$app->request->post('userName', '');
        $password = Yii::$app->request->post('password', '');
        if (empty($username) || empty($password)) {
          return Re::data(null, '参数错误', Re::ERROR);
        }
        $type = Yii::$app->request->post('type', 0);
        $user = Identity::findOne(['username'=>$username, 'status'=> 1]);
        if($user && Yii::$app->security->validatePassword($password, $user->password)){
            Yii::$app->user->login($user); // 这句不能丢，用户登录就，才能自动补全ar行为中的user_id
            $token = UserLogin::generateToken();
            return Re::data([
                'Authorization'=>'Bearer '.$token,
                'id' => $user->id,
                //'type' => $user->type,
                'username' => $user->username,
                //'header' => $user->showheader(),
                'first_access' => AuthItemChild::getFirstPermission($user->id, $type)->child,
                'role' => AuthItemChild::getFirstPermission($user->id, $type)->parent,
            ]);
        }else{
            return Re::data(null, '账号名或密码错误', Re::ERROR);
        }
    }

    /**
     * 后台用户列表
     */
    public function actionAdminList(){
        $status = Yii::$app->request->post('status', '-1');
        $role_name = Yii::$app->request->post('role', '-1');
        $keyword = Yii::$app->request->post('keyword', '');
        $page = Yii::$app->request->post('page', 0);
        $user_admin = User::findOne(Yii::$app->user->id);
        $user_query = User::find()
          ->leftJoin("auth_assignment", "auth_assignment.user_id = user.id")
          ->where(['is_admin' => 1, 'user.status' => [0,1]])
          ->andWhere("id <> $user_admin->id");
        if ($status > 0) {
            $user_query->andWhere(['status' => $status]);
        }
        if ($role_name > 0) {
          $user_query->andWhere(['item_name' => $role_name]);
        }
        if (!empty($keyword)) {
            $user_query->andWhere(['like', 'username', $keyword]);
        }
        $user_list = $user_query->limit(User::PAGE_SIZE)->offset($page*User::PAGE_SIZE)->all();
        $user_data = [];
        if ($user_list) {
          foreach ($user_list as $v) {
            $auth_assignment = AuthAssignment::find()->where(['user_id' => $v->id])->one();
            $user_data[] = [
              'id' => $v->id,
              'name' => $v->name,
              'username' => $v->username,
              'phone' => $v->phone,
              'header' => $v->header,
              'role' => $auth_assignment ? $auth_assignment->item_name : '',
              'status' => $v->status,
              'created_time' => date("Y-m-d H:i", $v->created_at),
            ];
          }
        }
        return Re::data([
            'data' => $user_data,
            'totalPage' => $user_query->count(),
            'currentPage' => $page,
            'perPage' => User::PAGE_SIZE
        ]);
    }

    /**
     * 后台用户创建/编辑
     */
    public function actionEditAdmin(){
        $id = Yii::$app->request->post('id', 0);
        $exa_id = Yii::$app->request->post('exa_id', 0);
        $post = Yii::$app->request->post();
        $post['username'] = $post['phone'];
        $post['is_admin'] = 1;
        $post['status'] = 1;
        $post['created_at'] = time();
        if(isset($post['type']) && $post['type'] == 10 && !Identity::checkAccess('manage_admin')){
            throw new ForbiddenHttpException('您无权限查看管理员');
        }
        if(isset($post['password']) && $post['password']){
            $post['password'] = Yii::$app->security->generatePasswordHash($post['password']);
        }
        $query = User::find()->where(['username' => $post['username']])->andWhere("status <> -1");
        if($id){
            $query->andWhere('id != :id', [':id'=>$id]);
        }
        if($query->exists()){
            return Re::data(null, '该账号已被使用', Re::ERROR);
        }
        if($id){
            $model = User::findOne($id);
            if(!$model){
                return Re::data(null, '您修改的数据不存在', Re::ERROR);
            }
        }else{
            $model = new User();
        }
        $auths = AuthItemChild::find()->where(['parent' => $post['role'], 'child' => 'live-list'])->one();
        if ($auths) {
            $post['type'] = 11;
        }
        //var_dump($post);die;
        $model->load($post, '');
        if($model->save()){
            if($model->username != 'admin' && isset($post['role']) && $post['role']){
                Yii::$app->authManager->revokeAll($model->id);
                Yii::$app->authManager->assign(
                    Yii::$app->authManager->getRole($post['role']), $model->id);
            }
            if(isset($post['password'])){
                $model->removeTokens();
            }
            return Re::data();
        }else{
            return Re::data(null, $model->showErrors(), Re::ERROR);
        }
    }

    /**
     * 后台用户状态修改
     */
    public function actionChangeUserStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $user = User::findOne($id);
        if (empty($user)) {
            return Re::data(null, '信息读取失败', Re::ERROR);
        }
        $user->status =  $status;
        if (!$user->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    /**
     * 后台用户状态密码
     */
    public function actionModifyPassword(){
        $password = Yii::$app->request->post('password', '');
        if (empty($password)) {
            return Re::data(null, '参数错误', Re::ERROR);
        }
        $user = User::findOne(Yii::$app->user->id);
        $user->password = Yii::$app->security->generatePasswordHash($password);
        if (!$user->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    /**
     * 前端用户列表
     */
    public function actionUserList(){
        $phone = Yii::$app->request->post('phone', '');
        $page = Yii::$app->request->post('page', 0);
        $user_query = User::find()->where(['status' => [0,1]])->andWhere("username <> 'admin'");
        if ($phone) {
            $user_query->andWhere(['like', 'phone', $phone]);
        }
        $user_list = $user_query->limit(User::PAGE_SIZE)->offset($page*User::PAGE_SIZE)->orderBy('created_at desc')->all();
        $user_data = [];
        if ($user_list) {
          foreach ($user_list as $v) {
            $user_data[] = [
              'id' => $v->id,
              'username' => $v->username,
              'phone' => $v->phone,
              'name' => $v->name,
              'is_admin' => $v->is_admin,
              'is_repair' => $v->repair_id,
              'repair_name' => $v->repair_id ? $v->repair->name : '',
              'form_selected' => $v->form_type_ids ? explode(',', $v->form_type_ids) : [],
              'status' => $v->status,
              'created_time' => date("Y-m-d H:i", $v->created_at),
            ];
          }
        }
        return Re::data([
            'data' => $user_data,
            'totalPage' => $user_query->count(),
            'currentPage' => $page,
            'perPage' => User::PAGE_SIZE
        ]);
    }

    public function actionChangeUserIdentity(){
        $id = Yii::$app->request->post('id', 0);
        $type = Yii::$app->request->post('type', 1);
        $repair_id = Yii::$app->request->post('repair_id', 0);
        $user = User::findOne($id);
        if ($type == 1) {
          $user->is_admin = $user->is_admin ? 0 : 1;
        } else {
          $user->repair_id = $user->repair_id ? 0 : $repair_id;
        }
        $user->save();
        return Re::data();
    }

    public function actionUserAuthList(){
        $phone = Yii::$app->request->post('phone', '');
        $company_name = Yii::$app->request->post('company_name', '');
        $audit_status = Yii::$app->request->post('audit_status', -2);
        $page = Yii::$app->request->post('page', 0);
        $user_auth_query = UserAuthRecord::find()
          ->leftJoin("user", "user_auth_record.user_id = user.id")
          ->leftJoin("company_info", "user_auth_record.company_id = company_info.id")
          ->where(['user_auth_record.status' => 1]);
        if ($phone) {
            $user_auth_query->andWhere(['like', 'user.phone', $phone]);
        }
        if ($company_name) {
            $user_auth_query->andWhere(['like', 'company_info.name', $company_name]);
        }
        if ($audit_status > -1) {
            $user_auth_query->andWhere(['audit_status' => $audit_status]);
        }
        $user_auth_list = $user_auth_query->limit(UserAuthRecord::PAGE_SIZE)->offset($page*UserAuthRecord::PAGE_SIZE)->orderBy('created_at desc')->all();
        $user_auth_data = [];
        if ($user_auth_list) {
          foreach ($user_auth_list as $v) {
            $user_auth_data[] = [
              'id' => $v->id,
              'phone' => $v->user->phone,
              'name' => $v->user->name,
              'company_id' => $v->companyInfo->id,
              'company_name' => $v->companyInfo->name,
              'company_address' => $v->companyInfo->address,
              'company_code' => $v->companyInfo->code,
              'company_code_img' => $v->companyInfo->code_img,
              'audit_status' => $v->audit_status,
              'created_time' => date("Y-m-d H:i", $v->created_at),
            ];
          }
        }
        return Re::data([
            'data' => $user_auth_data,
            'totalPage' => $user_auth_query->count(),
            'currentPage' => $page,
            'perPage' => UserAuthRecord::PAGE_SIZE
        ]);
    }

    public function actionAuditUserAuth(){
        $id = Yii::$app->request->post('id', 0);
        $audit_status = Yii::$app->request->post('audit_status', 1);
        $remark = Yii::$app->request->post('remark', '');
        $user_auth = UserAuthRecord::findOne($id);
        $user_auth->audit_status = $audit_status;
        $user_auth->remark = $remark;
        $user_auth->save();
        if ($audit_status == 1) {
          $user_auth->user->name = $user_auth->name;
          $user_auth->user->company_id = $user_auth->company_id;
          $user_auth->user->save();
        }
        return Re::data();
    }

    public function actionChangeUserAuthStatus(){
        $id = Yii::$app->request->post('id', 0);
        $user_auth = UserAuthRecord::findOne($id);
        $user_auth->user->company_id = 0;
        $user_auth->user->save();
        //$user_auth->companyInfo->delete();
        $user_auth->delete();
        return Re::data();
    }

    public function actionEditUserAuth(){
        $id = Yii::$app->request->post('id', 0);
        $company_name = Yii::$app->request->post('company_name', '');
        $company_address = Yii::$app->request->post('company_address', '');
        $company_code = Yii::$app->request->post('company_code', '');
        $company_code_img = Yii::$app->request->post('company_code_img', '');
        $companyInfo = CompanyInfo::findOne($id);
        if (!$companyInfo) {
          return Re::data(null, '信息读取失败', Re::ERROR);
        }
        $companyInfo->name = $company_name;
        $companyInfo->address = $company_address;
        $companyInfo->code = $company_code;
        $companyInfo->code_img = $company_code_img;
        if (!$companyInfo->save()) {
          return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionUserAddressList(){
        $name = Yii::$app->request->post('name', '');
        $phone = Yii::$app->request->post('phone', '');
        $page = Yii::$app->request->post('page', 0);
        $address_query = Address::find()->where(['status' => 1]);
        if ($name) {
            $address_query->andWhere(['like', 'name', $name]);
        }
        if ($phone) {
            $address_query->andWhere(['like', 'phone', $phone]);
        }
        $address_list = $address_query->limit(Address::PAGE_SIZE)->offset($page*Address::PAGE_SIZE)->all();
        $address_data = [];
        if ($address_list) {
          foreach ($address_list as $v) {
            $address_data[] = [
              'id' => $v->id,
              'name' => $v->name,
              'phone' => $v->phone,
              'address' => $v->address,
              'default' => $v->default,
              'created_time' => date("Y-m-d H:i", $v->created_at),
            ];
          }
        }
        return Re::data([
            'data' => $address_data,
            'totalPage' => $address_query->count(),
            'currentPage' => $page,
            'perPage' => Address::PAGE_SIZE
        ]);
    }

    public function actionSetAdminForm(){
        $id = Yii::$app->request->post('id', 0);
        $form_selected_ids = Yii::$app->request->post('form_selected_ids', '');
        $user = User::findOne($id);
        if (!$user) {
          return Re::data(null, '管理员信息读取失败', Re::ERROR);
        }
        $user->form_type_ids = $form_selected_ids;
        $user->save();
        return Re::data();
    }

    private function getExStatus($user_id) {
      $ex_status = 1;
      if ($user_id) {
        $exhibitionApply = ExhibitionApply::find()->where(['user_id' => $user_id])->one();
        if ($exhibitionApply) {
          $exa_id = $exhibitionApply->id;
          $exhibitionBrand = ExhibitionBrand::find()->where(['exa_id' => $exa_id])->one();
          if ($exhibitionBrand) {
            $ex_status = $exhibitionBrand->status;
          }
        }
      }
      return $ex_status;
    }
}
